package cn.wolfcode.wolf2w.gateway.filter;

import cn.wolfcode.wolf2w.common.core.domain.R;
import cn.wolfcode.wolf2w.gateway.util.Md5Util;
import com.alibaba.fastjson.JSON;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class SignFilter implements GlobalFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        MultiValueMap<String, String> queryParams = exchange.getRequest().getQueryParams();
        Map<String, Object> map = new HashMap<>();
        for (String key : queryParams.keySet()) {
            if ("sign".equals(key)) {
                continue;
            }
            List<String> list = queryParams.get(key);
            StringBuffer stringBuffer = new StringBuffer();
            for (String s : list) {
                stringBuffer.append(s);
            }
            String value = stringBuffer.toString();
            map.put(key, value);
        }
        String sign_server = Md5Util.signatures(map);
        String sign_client = queryParams.getFirst("sign");

        //为了测试,以后每个接口传递sign参数，此时将下面代码注释
        if (sign_client == null || "".equals(sign_client)) {

            return chain.filter(exchange);
        }

        if (!sign_client.equals(sign_server)) {
            exchange.getResponse().getHeaders().setContentType(MediaType.APPLICATION_JSON);
            R<Object> r = R.fail(500, "参数呗篡改");
            String jsonString = JSON.toJSONString(r);
            DataBuffer dataBuffer = exchange.getResponse().bufferFactory().wrap(jsonString.getBytes(StandardCharsets.UTF_8));
            return exchange.getResponse().writeWith(Mono.just(dataBuffer));

        }

        String timestamp = queryParams.getFirst("timestamp");
        Long client_time = Long.valueOf(timestamp);
        long server_time = System.currentTimeMillis();
        if (server_time - client_time > 0.5 * 60 * 1000) {
            exchange.getResponse().getHeaders().setContentType(MediaType.APPLICATION_JSON);
            R<Object> r = R.fail(500, "接口访问超时");
            String jsonString = JSON.toJSONString(r);
            DataBuffer dataBuffer = exchange.getResponse().bufferFactory().wrap(jsonString.getBytes(StandardCharsets.UTF_8));
            return exchange.getResponse().writeWith(Mono.just(dataBuffer));

        }
        return chain.filter(exchange);
    }
}
